<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import { statisticsWorkYearsInfo } from '@/api/charts'
import resize from './mixins/resize'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    }
  },
  data() {
    return {
      chart: null,
      workYearsInfo: [
        { 'le0': '无工作经验' },
        { 'le1': '1年以下' },
        { 'le3': '1-3年' },
        { 'le5': '3-5年' },
        { 'le10': '5-10年' },
        { 'le99': '10年以上' },
        { 'le999': '不限' }
      ]
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
    statisticsWorkYearsInfo().then(response => {
      const xaxisData = []
      const mixData = []
      this.workYearsInfo.forEach(item => {
        const tg = Object.keys(item)[0]
        xaxisData.push(item[tg])
        mixData.push({ value: response.result[tg], name: item[tg] })
      })
      this.initChart(xaxisData, mixData)
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart(xaxisData, mixData) {
      this.chart = echarts.init(this.$el, 'macarons')

      this.chart.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)',
          position: function(p) {
            return [p[0] + 10, p[1] - 10]
          },
          extraCssText: 'width:160px;height:54px;'
        },
        legend: {
          left: 'center',
          top: 'bottom',
          data: xaxisData
        },
        series: [
          {
            name: '经验要求',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: true,
            data: mixData
          }
        ]
      })
    }
  }
}
</script>
